<template>
	<view class="content">
		<view class="pay_price">
			<view>
				<text class="unit">
					￥
					<text class="price">{{ Payinfo.money || '0.00' }}</text>
				</text>
			</view>
			<text class="text-content">支付剩余时间14:55</text>
		</view>
		<view class="pay_back">
			<view>
				<u--image :showLoading="true" src="../../static/Mine/wx.png" width="48rpx" height="48rpx"
					radius="0"></u--image>
				<text>微信支付</text>
			</view>
			<label class="radio">
				<radio value="r1" checked="true" style="transform: scale(0.8)" />
			</label>
		</view>
		<button class="pay" @click="course" v-if="Payinfo.content.length > 0"
			:style="{ background: $store.state.buttonColor }">确认支付</button>
		<button class="pay" @click="Teacherpay" v-else :style="{ background: $store.state.buttonColor }">确认支付</button>

		<u-popup :show="iSshow" @close="iSshow = false" @open="iSshow = true" mode="bottom" :closeable="false"
			:round="50">
			<view class="popupBody">
				<view class="headersBody">
					<u-icon name="close" color="#ebf7ff" size="20"></u-icon>
					<text>分享二维码</text>
					<u-icon name="close" color="#888888" size="20" @click="iSshow = false"></u-icon>
				</view>
				<view class="qrcode">
					<image id="qrcode" :src="qrUrl" style="width: 200px; height: 200px"></image>
				</view>
				<view class="buttonFlex">
					<button class="leftButton" @click="copy">复制链接</button>
					<button class="rightButton" @click="save_img"
						:style="{ background: $store.state.buttonColor }">长按保存</button>
				</view>
			</view>
		</u-popup>
		<canvas id="qrcode" canvas-id="qrcode" style="width: 200px; height: 200px; z-index: -999"></canvas>
	</view>
</template>

<script>
	import {
		Teacherpay,
		fitness_course_add,
		getJsSdk
	} from '../../api/Teacher.js';
	import UQRCode from '../../uni_modules/Sansnn-uQRCode/js_sdk/uqrcode/uqrcode.js';
	import jWeixin from '../../js_sdk/jweixin-module';
	export default {
		data() {
			return {
				iSshow: false,
				Payinfo: {},
				size: 200, // 二维码尺寸
				qrUrl: ''
			};
		},
		onLoad(options) {
			this.Payinfo = {
				...JSON.parse(options.payinfo)
			};
			if (!this.Payinfo.content) {
				this.Teacherpay();
			} else {
				this.fitness_course_add();
			}
		},
		// onReady() {
		// 	this.generate()
		// },
		methods: {
			saveQRCodeImage() {
				const canvasId = 'qrcode'; // Canvas ID，与UQRCode绑定的Canvas ID保持一致
				uni.canvasToTempFilePath({
					canvasId: canvasId,
					success: (res) => {
						console.log('二维码图片临时文件路径:', res.tempFilePath);
						let base64Data = res.tempFilePath.replace(/[\r\n]/g, '');
						this.qrUrl = base64Data;
						console.log(base64Data);
					},
					fail: (error) => {
						console.error('获取二维码图片失败:', error);
						uni.showToast({
							title: '获取二维码失败',
							icon: 'none'
						});
					}
				});
			},
			copy() {
				uni.setClipboardData({
					data: `https://yuekewap.worldtalker.cn/#/pages/Order/pay_share?order_id=${this.Payinfo.order_id}`,
					success: function() {
						uni.showToast({
							title: '复制成功！',
							icon: 'none',
							duration: 2000
						});
					}
				});
			},
			generate() {
				var qr = new UQRCode();
				qr.data = `https://yuekewap.worldtalker.cn/#/pages/Order/pay_share?order_id=${this.Payinfo.order_id}`;
				qr.size = 200;
				qr.make();
				var canvasContext = uni.createCanvasContext('qrcode', this);
				qr.canvasContext = canvasContext;
				qr.drawCanvas();
				this.saveQRCodeImage();
			},
			/**
			@method 购买固定课程
			**/
			async fitness_course_add() {
				try {
					const res = await fitness_course_add(this.Payinfo);
					this.Payinfo = {
						...this.Payinfo,
						...res.data,
						...{
							money: res.data.pay_price
						}
					};
				} catch (err) {
					//TODO handle the exception
					console.log(err);
				}
			},
			course() {
				this.wxH5pay(this.Payinfo);
			},
			async share() {
				try {
					var th_is = this;
					const res = await getJsSdk({
						url: '/pages/Order/pay'
					});
					jWeixin.config({
						debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
						appId: res.data['appId'], // 必填，公众号的唯一标识
						timestamp: res.data['timestamp'], // 必填，生成签名的时间戳
						nonceStr: res.data['nonceStr'], // 必填，生成签名的随机串
						signature: res.data['signature'], // 必填，签名
						jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData'] // 必填，需要使用的JS接口列表
					});
					jWeixin.ready(function() {
						// 分享给朋友
						jWeixin.updateAppMessageShareData({
							title: '约课', // 分享标题
							desc: '邀请您参加1v2预约课程', // 分享描述
							link: `${window.location.href}?order_id=${th_is.Payinfo.order_id}`, // 分享链接
							imgUrl: '', // 分享图标
							type: 'link', // 分享类型,music、video或link，不填默认为link
							success: function() {
								// 分享成功回调
							}
						});
						// 分享到朋友圈
						jWeixin.updateTimelineShareData({
							title: '约课', // 分享标题
							desc: '邀请您参加1v2预约课程', // 分享描述
							link: `${window.location.href}?order_id=${th_is.Payinfo.order_id}`, // 分享链接
							imgUrl: '', // 分享图标
							success: function() {
								// 分享成功回调
							}
						});
					});
				} catch (err) {
					//TODO handle the exception
					console.log(err);
				}
			},
			/**
			@method 保存图片
			**/
			save_img(href) {
				// // 创建一个隐藏的链接元素
				const link = document.createElement('a');
				link.href = this.qrUrl;
				// 指定下载的文件名
				link.download = '分享二维码';
				// 将链接元素添加到 DOM
				document.body.appendChild(link);
				// 模拟点击链接以触发下载
				link.click();
				// 下载完成后移除链接元素
				document.body.removeChild(link);
				// uni.canvasToTempFilePath({
				// 	x: 100,
				// 	y: 200,
				// 	width: 50,
				// 	height: 50,
				// 	destWidth: 100,
				// 	destHeight: 100,
				// 	canvasId: 'qrcode',
				// 	success: function (res) {
				// 		console.log(res)
				// 		const aEle = document.createElement('a')
				// 		aEle.download = 'uQRCode' // 设置下载的文件名，默认是'下载'
				// 		aEle.href = res.tempFilePath
				// 		uni.saveImageToPhotosAlbum({
				// 			filePath: res.tempFilePath,
				// 			success: () => {
				// 				uni.showToast({
				// 					title: '保存成功',
				// 					icon: 'success'
				// 				})
				// 			}
				// 		})
				// 		document.body(aEle)
				// 		aEle.click()
				// 		aEle.remove() // 下载之后把创建的元素删除
				// 	}
				// })
			},
			/**
			@method 支付
			**/
			async Teacherpay() {
				try {
					const res = await Teacherpay(this.Payinfo);
					if (res.code == 0 || res.code == '0') {
						setTimeout(() => {
							uni.switchTab({
								url: '/pages/Tabbar/Home/Home'
							});
						}, 2000);
					} else {
						this.wxH5pay(res.data);
					}

				} catch (err) {
					//TODO handle the exception
					console.log(err);
				}
			},
			wxH5pay(res) {
				var _this = this;
				jWeixin.config({
					debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,线上环境需要改为false
					appId: res.appId, // 必填，公众号的唯一标识
					timestamp: res.timestamp, // 必填，生成签名的时间戳
					nonceStr: res.nonceStr, // 必填，生成签名的随机串
					signature: res.paySign, // 必填，签名
					jsApiList: ['chooseWXPay'] // 必填，需要使用的JS接口列表
				});
				jWeixin.ready(() => {
					jWeixin.chooseWXPay({
						appId: res.appId, // 必填，公众号的唯一标识
						timestamp: res.timestamp,
						nonceStr: res.nonceStr, // 支付签名随机串，不长于 32 位
						package: res.package, // 统一支付接口返回的prepay_id参数值
						signType: res.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
						paySign: res.paySign, // 支付签名
						success: function(res) {
							//支付成功回调
							console.log('支付成功');
							uni.showToast({
								title: '支付成功',
								icon: 'none',
								duration: 2000
							});
							if (_this.Payinfo.type == 2 || _this.Payinfo.type == '2') {
								_this.iSshow = true;
								_this.$nextTick(() => {
									_this.generate();
								});
							} else {
								uni.reLaunch({
									url: '/pages/Order/pay_status?PayType=success'
								});
							}
						},
						cancel: function(res) {
							uni.showToast({
								title: '取消支付',
								icon: 'none',
								duration: 2000
							});
							alert('取消支付');
						},
						fail: function(res) {
							console.log('fail', res);
							uni.showToast({
								title: '支付失败',
								icon: 'none',
								duration: 2000
							});
							uni.reLaunch({
								url: '/pages/Order/pay_status?PayType=fail'
							});
						}
					});
				});
			}
		}
	};
</script>

<style>
	page {
		background-color: #f7f7f7;
	}
</style>
<style scoped lang="scss">
	.qrcode {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 400rpx;
		// canvas {
		// 	border: 1px solid #000 !important;
		// }
	}

	button::after {
		border: none;
	}

	.content {
		#qrcode {
			margin: 0rpx auto;
			margin-top: 50rpx;
		}

		.pay_price {
			view {
				width: 100%;
				display: flex;
				justify-content: center;
				margin-top: 100rpx;
				margin-bottom: 10rpx;
			}

			.unit {
				font-family: PingFangSC, PingFang SC;
				font-weight: 500;
				font-size: 40rpx;
				color: #202020;
				text-align: center;
			}

			.price {
				font-family: PingFangSC, PingFang SC;
				font-weight: 600;
				font-size: 80rpx;
				color: #202020;
				text-align: center;
			}

			.text-content {
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				font-size: 24rpx;
				color: #888888;
				text-align: center;
				display: block;
			}
		}

		.pay_back {
			width: 85%;
			padding: 30rpx;
			background-color: #fff;
			margin: 0px auto;
			display: flex;
			border-radius: 20rpx;
			justify-content: space-between;
			align-items: center;
			margin-top: 100rpx;

			view {
				display: flex;
				align-items: center;

				text {
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: 28rpx;
					color: #101010;
					margin-left: 20rpx;
				}
			}
		}

		.pay {
			width: 95%;
			height: 96rpx;
			position: fixed;
			bottom: 20rpx;
			left: 2.5%;
			// background-color: #2183fe;
			color: #fff;
			display: flex;
			justify-content: center;
			align-items: center;
			font-family: PingFangSC, PingFang SC;
			font-weight: 500;
			font-size: 32rpx;
			color: #ffffff;
			border-radius: 50rpx;
		}

		.popupBody {
			.headersBody {
				display: flex;
				justify-content: space-between;
				background-color: #ebf7ff;
				padding: 30rpx;
				border-top-left-radius: 30rpx;
				border-top-right-radius: 30rpx;

				text {
					font-family: PingFangSC, PingFang SC;
					font-weight: 600;
					font-size: 32rpx;
					color: #202020;
				}
			}

			.Newqrcode {
				width: auto;
				height: auto;
				margin: 0px auto;
				// background-color: #000000;
				margin-top: 40rpx;
			}

			.buttonFlex {
				margin-top: 100rpx;
				margin-bottom: 10rpx;
				display: flex;
				align-items: center;
				justify-content: space-around;

				.leftButton {
					width: 40%;
					height: 75rpx;
					margin: 0px;
					background-color: #efefef;
					color: #333;
					display: flex;
					justify-content: center;
					align-items: center;
					border-radius: 50rpx;
					font-size: 28rpx;
					letter-spacing: 2rpx;
				}

				.rightButton {
					width: 40%;
					height: 75rpx;
					margin: 0px;
					// background-color: #277ffe;
					color: #fff;
					display: flex;
					justify-content: center;
					align-items: center;
					border-radius: 50rpx;
					font-size: 28rpx;
					letter-spacing: 2rpx;
				}
			}
		}
	}
</style>